package com.rtx.wms.std.handler.asn;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.model.emums.SysNumberType;
import com.rtx.wms.std.asn.bean.ApiReceipt;
import com.rtx.wms.std.asn.bean.ApiReceiptdetail;
import com.rtx.wms.std.asn.bean.Receipt;
import com.rtx.wms.std.asn.bean.Receiptdetail;
import com.rtx.wms.std.asn.service.ApiReceiptService;
import com.rtx.wms.std.asn.service.ReceiptService;
import com.rtx.wms.std.common.bean.Codelkup;
import com.rtx.wms.std.common.bean.Storer;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.common.service.CommonService;
import com.rtx.wms.std.ctclass.EdiDynamicsHelp;
import com.rtx.wms.std.storer.service.StorerService;

import cn.hutool.core.util.StrUtil;

@Component
public class ReceiptDownHandler {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ApiReceiptService apiReceiptService;

	@Autowired
	private ReceiptService receiptService;

	@Autowired
	private CommonService commonService;
	
	@Autowired
	StorerService  storerService;

	/**
	 * 入库单从中间表写入WMS
	 * @param whseid
	 */
	public void handlerReceiptToWms(String whseid,ApiMappingInfoBo bo){
		//获取中间表未处理成功的订单
		List<ApiReceipt> receiptList = selectApiReceipt("ris_edi",bo);
		if(CollectionUtils.isEmpty(receiptList)){
			return;
		}
		for(ApiReceipt o : receiptList){
			//添加wms入库单
			addWmsReceipt(whseid,o,bo);
			//更新中间表状态
			updateApiReceipt("ris_edi",o);
		}
	}


	/**
	 * 更新中间表
	 * @param whseid
	 * @param apiReceipt
	 */
	private void updateApiReceipt(String whseid,ApiReceipt apiReceipt) {
		LambdaUpdateWrapper<ApiReceipt> update = Wrappers.lambdaUpdate();
		update.eq(ApiReceipt::getSerialkey,apiReceipt.getSerialkey())
		.set(ApiReceipt::getEdiflag,apiReceipt.getEdiflag())
		.set(ApiReceipt::getEdimsg,StrUtil.sub(apiReceipt.getMsg(), 0, 498))
		.set(ApiReceipt::getRtxqueue,apiReceipt.getRtxqueue() + 1);
		apiReceiptService.updateByWrapper(whseid,update);
	}

	/**
	 * 添加wms入库单
	 * @param whseid
	 * @param apiReceipt
	 */
	void addWmsReceipt(String whseid,ApiReceipt apiReceipt,ApiMappingInfoBo bo){
		try {
			whseid = apiReceipt.getWhseid();
			
			Receipt receipt = convertReceipt(apiReceipt.getWhseid(),apiReceipt,bo);
			
			//匹配入库单类型
			mappingReceiptType(whseid,receipt);
			
			//设置是否允许超收
			mappingStorerTypeAllowover(whseid,receipt);
			
			receiptService.handlerExistsReceipt(whseid, receipt.getExternreceiptkey());
			//新增入库单
			receiptService.addReceipt(whseid,receipt,bo);
			apiReceipt.setEdiflag(WmsConstant.SUCCESS_FLAG);
		} catch (Exception e) {
			logger.error("仓库{}，批次号{}从中间表写入WMS异常",whseid,apiReceipt.getBatchid(),e);
			apiReceipt.setEdiflag(WmsConstant.FAIL_FLAG);
			apiReceipt.setEdimsg(e.getMessage());
		}
	}
	
	
	
	
	//是否允许超收
	private void mappingStorerTypeAllowover(String datasourcekey,Receipt receipt) {
		Storer storer = Optional.ofNullable(storerService.queryByStorerByDatasource(receipt.getWhseid(), receipt.getStorerkey())).orElse(new Storer());
		if("1".equals(receipt.getType())) {
			if(null == storer.getAllowOver()) {
				receipt.setAllowOver(0+"");
			}else {
				receipt.setAllowOver(storer.getAllowOver()+"");
			}

		}
	}

	/**
	 * 匹配入库单类型
	 * @param wmwhseid
	 * @param orders
	 */
	private void mappingReceiptType(String wmwhseid,Receipt receipt) {
		String qmtype = receipt.getRtxqmtype();
		Codelkup soTypeMapping = Optional.ofNullable(commonService.selectCodelkupByCodeAndListname(wmwhseid, qmtype, "RTXASNTYPEMAPPING")).orElse(new Codelkup()) ;
		if(StringUtils.hasLength(soTypeMapping.getUdf1())) {
			receipt.setType(soTypeMapping.getUdf1());
		}
	}

	/**
	 * 获取中间表未处理成功的订单
	 * @param whseid
	 * @return
	 */
	private List<ApiReceipt> selectApiReceipt(String whseid,ApiMappingInfoBo bo) {
		//获取中间表未处理成功的订单
		LambdaQueryWrapper<ApiReceipt> query = Wrappers.lambdaQuery();
		query.in(ApiReceipt::getEdiflag, WmsConstant.DEFAULT_FLAG,WmsConstant.FAIL_FLAG)
		.lt(ApiReceipt::getRtxqueue,30)
		.last("limit 500");
		return apiReceiptService.selectApiReceiptByWrapper(whseid, query,bo);
	}

	/**
	 * 转化类型
	 * @param o
	 * @return
	 */
	private Receipt convertReceipt(String whseid,ApiReceipt o,ApiMappingInfoBo bo) {
		//获取wms单号
		//String receiptkey = commonService.getWmsKey(o.getWhseid(),"R", "RECEIPT");
		String receiptkey = commonService.getWmsKey(whseid, SysNumberType.SysNumberType2);
		Receipt receipt = (Receipt) EdiDynamicsHelp.createObjectByConfig(bo, Receipt.class, "main_link");
		BeanUtils.copyProperties(o,receipt,"details");
		receipt.setReceiptkey(receiptkey);
		receipt.setStatus("0");
		receipt.setEdiflag("P");
		Double totalQty = 0D;
		int line = 1;
		List<Receiptdetail> details = new ArrayList<>();
		for(ApiReceiptdetail od : o.getDetails()){
			Receiptdetail detail = (Receiptdetail) EdiDynamicsHelp.createObjectByConfig(bo, Receiptdetail.class, "sub_link");
			BeanUtils.copyProperties(od,detail);
			detail.setReceiptkey(receiptkey);
			detail.setStatus("0");
			detail.setUom("EA");
			totalQty += od.getQtyexpected();
			detail.setReceiptlinenumber(String.format("%05d",line++));
			detail.setSerialkey(null);
			detail.setQtyexpected(od.getQtyexpected());
			details.add(detail);
		}
		receipt.setCarrierreference(o.getRtxexpresskey());
		receipt.setOpenqty(new BigDecimal(totalQty));
		receipt.setDetails(details);
		return receipt;
	}
}
